<?php
namespace Infinity;

class File {

  private $file;

  public function __construct($file_or_fid) {
    if(is_object($file_or_fid))
      $this->file = $file_or_fid;
    if(is_numeric($file_or_fid))
      $this->file = file_load($file_or_fid);
  }
  /*
url = 'http://s1.bdstatic.com/r/www/cache/static/global/img/icons_1529edac.png';
$file = Infinity\File::getRemoteImage($url);
$file = file_save($file);
$profile = profile2_load_by_user(820, 'general');
$profile->field_user_image[LANGUAGE_NONE][0] = (array)$file;
profile2_save($profile);
   */
  public static function getRemoteImage($url, $save_path='public://'){
    $file = new \stdClass;
    $file->filepath = $url;

    $result = drupal_http_request($file->filepath);

    if ($result->code == 200) {
      if (!file_prepare_directory($save_path, FILE_CREATE_DIRECTORY)) {
        watchdog('file', 'The upload directory %directory for the file field !name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.', array('%directory' => $save_path, '!name' => $url));
        return FALSE;
      }

      $file->uid = $GLOBALS['user']->uid;
      $file->filename = basename($file->filepath);
      $file->status = 0;
      $file->timestamp = time();

      $file->extension = strtolower(ltrim(substr($file->filename, -4), '.'));

      if (!in_array($file->extension, array('png', 'gif', 'jpeg', 'jpg'))) {
        if (!empty($result->headers['content-type'])) {
          $arr = explode('/', $result->headers['content-type']);
          $file->extension = end($arr);
        } else {
          $file->extension = 'jpg';
        }
      }

      $file->filename = md5($file->filename.time()) . '.' . $file->extension;

      $file->filepath = $save_path . $file->filename;
      $file->uri = $file->filepath;
      $file->destination = $file->filename;
      $file->status = FILE_STATUS_PERMANENT;
      if (file_put_contents($file->filepath, $result->data)) {
        return $file;
      }
    }
    return false;
  }

  public static function loadFromPath($path) {
    if(file_exists($path)) {
      $file = (object) array(
        'uid' => $GLOBALS['user']->uid,
        'uri' => $path,
        'filemime' => file_get_mimetype($path),
        'status' => 1,
        'display' => 1,
      );
      return new File($file);
    }
    return false;
  }

  public function copy($new_path) {
    if (!file_prepare_directory($new_path, FILE_CREATE_DIRECTORY)) {
      watchdog('file', 'The upload directory %directory for the file field !name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.', array('%directory' => $new_path, '!name' => $new_path));
      return FALSE;
    }
    $file = file_copy($this->file, $new_path);
    return new File($file);
  }

  public function isEmpty() {
    return empty($this->file);
  }

  public function getData() {
    return $this->file;
  }

  public function save() {
    $this->file = file_save($this->file);
  }

  public function output() {
    if(!$this->isEmpty()) {
      file_transfer($this->file->uri, array('Content-Type' => 'application/octet-stream',
        'Content-Disposition' => 'attachment; filename="' . basename($this->file->uri). '"',
        'Content-Length' => filesize($this->file->uri)));
      drupal_exit();
    } else {
      die('file is empty');
    }
  }

  public static function isExists($uri) {
    return file_exists(drupal_realpath($uri));
  }
}